package com.shop.cereshop.agent.job;

import com.shop.cereshop.commons.domain.rank.AgentRank;
import com.shop.cereshop.agent.dao.referral.AgentReferralDAO;
import com.shop.cereshop.agent.page.rank.RankItem;
import com.shop.cereshop.agent.service.rank.AgentRankService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description: 排行榜定时任务
 * @author lx
 * @date 2025/10/18 19:33
 * @version 1.0
 */
@Component
@Order(1)
@Slf4j
@RequiredArgsConstructor
public class RankJob {

  private Integer page = 1;

  private Integer pageSize = 50;

  private final AgentReferralDAO agentReferralDAO;

  private final AgentRankService agentRankService;

  /**
   * 每天存储排行榜数据定时任务(每天凌晨1点更新)
   */
  @XxlJob("applyDayRank")
  @Scheduled(cron = "0 0 1 * * ?")
  public void applyDayRank() {
    log.info("开始执行定时任务每日排行榜");
    // 当前时间
    long startTime = System.currentTimeMillis();

    // 1、查询当前时间为止的排行榜
    // 优化：通过一次SQL查询获取所有数量类型的排行榜数据
    List<RankItem> allNumRankItems = agentReferralDAO.getAllNumRankData();

    // 按照rankType将数据分类
    Map<Integer, List<RankItem>> rankDataByType = new HashMap<>();
    if (allNumRankItems != null && !allNumRankItems.isEmpty()) {
      rankDataByType = allNumRankItems.stream()
          .collect(Collectors.groupingBy(RankItem::getRankType));
    }

    // 提取各类排行榜数据（每种类型只取前50名，并设置排名）
    List<RankItem> shopNumList = getTop50WithRank(rankDataByType.getOrDefault(1, new ArrayList<>())); // 商家数量榜
    List<RankItem> userNumList = getTop50WithRank(rankDataByType.getOrDefault(3, new ArrayList<>())); // 用户数量榜
    List<RankItem> agentNumList = getTop50WithRank(rankDataByType.getOrDefault(6, new ArrayList<>())); // 代理商推广榜
    List<RankItem> salespersonNumList = getTop50WithRank(rankDataByType.getOrDefault(5, new ArrayList<>())); // 业务员推广榜

    // 处理金额排行榜（每种类型只取前50名，并设置排名）
    List<RankItem> shopAmountList = getTop50WithRank(agentReferralDAO.getShopAmount());
    List<RankItem> userAmountList = getTop50WithRank(agentReferralDAO.getUserAmount());

    // 2、存入每日排行榜数据表里
    // 优化：合并所有数据为一个列表，一次性批量插入，减少数据库连接次数
    List<AgentRank> allRankData = new ArrayList<>();

    // 获取当日前一天日期
    LocalDate yesterday = LocalDate.now().minusDays(1);

    // 添加各类排行榜数据
    allRankData.addAll(convertToAgentRank(shopNumList, yesterday, 1)); // 商家数量榜
    allRankData.addAll(convertToAgentRank(userNumList, yesterday, 3)); // 用户数量榜
    allRankData.addAll(convertToAgentRank(agentNumList, yesterday, 6)); // 代理商推广榜
    allRankData.addAll(convertToAgentRank(salespersonNumList, yesterday, 5)); // 业务员推广榜
    allRankData.addAll(convertToAgentRank(shopAmountList, yesterday, 2)); // 商家成交额榜
    allRankData.addAll(convertToAgentRank(userAmountList, yesterday, 4)); // 用户成交额榜

    // 一次性批量存储所有排行榜数据
    if (!allRankData.isEmpty()) {
      agentRankService.saveOrUpdateBatch(allRankData);
    }

    // 结束时间
    long endTime = System.currentTimeMillis();
    log.info("定时任务执行完成，耗时：{}ms", endTime - startTime);

    log.info("排行榜数据获取完成: 商家数量={}, 用户数量={}, 代理商数量={}, 业务员数量={}, 商家金额={}, 用户金额={}",
        shopNumList.size(), userNumList.size(), agentNumList.size(), salespersonNumList.size(),
        shopAmountList.size(), userAmountList.size());
  }

  /**
   * 获取列表的前50名数据并设置排名
   */
  private List<RankItem> getTop50WithRank(List<RankItem> list) {
    // 只取前50名
    List<RankItem> top50 = list.size() > 50 ? list.subList(0, 50) : list;

    // 设置排名
    for (int i = 0; i < top50.size(); i++) {
      top50.get(i).setRankLevel(i + 1);
    }

    return top50;
  }

  /**
   * 将RankItem列表转换为AgentRank列表
   */
  private List<AgentRank> convertToAgentRank(List<RankItem> rankItems, LocalDate statDate, Integer rankType) {
    return rankItems.stream().map(item -> {
      AgentRank agentRank = new AgentRank();
      agentRank.setAgentUserId(item.getAgentUserId());
      agentRank.setStatValue(item.getStatValue());
      agentRank.setRankLevel(item.getRankLevel());
      agentRank.setStatDate(statDate);
      agentRank.setStatCycle(1); // 日排行榜
      agentRank.setRankType(rankType);
      return agentRank;
    }).collect(Collectors.toList());
  }
}